package com.mediacloud.app.newsmodule.fragment.ebook

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.fbnavsk.navPaddingTopMatch
import com.mediacloud.app.model.news.CatalogItem
import com.mediacloud.app.nav2.fragment.HqyNavFragment
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.ReadBookInfoActivity
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter
import com.mediacloud.app.newsmodule.fragment.baoliao.api.SpiderCmsApi
import com.mediacloud.app.quanzi.model.BaseDataListBean
import com.mediacloud.app.reslib.enums.ToolBarActionF5OrTop
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.ebook_fragment.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.textColor
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.lang.StringBuilder

/**
 * 电子书导航
 */
class EBookFragment : HqyNavFragment(), BaseRecyclerAdapter.ItemClickListener,
    ToolBarActionF5OrTop {

    val LOGIN = 1
    val REFRESH = 2
    var Mode = REFRESH

    var catalogItem: CatalogItem? = null
    var catalogID: String? = null//导航id
    var pageIndex = 1
    var perPageSize = 20
    var catId:String = ""//栏目id
    lateinit var ebookAdapter: EbookListAdapter
    lateinit var oneLineAdapter: CategoryAdapter
    lateinit var twoLineAdapter: CategoryAdapter
    lateinit var threeLineAdapter: CategoryAdapter
    private var chooseType: Boolean = false


    override fun getLayoutResID(): Int {
        return R.layout.ebook_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this.navPaddingTopMatch()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView() {
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {

                loadMore()
            }
        })
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        ebookAdapter = EbookListAdapter(activity)
        ebookAdapter.setItemClickListener(this)
        recyclerView.adapter = ebookAdapter
        loadingView = mRootView.findViewById(R.id.mLoadingView)
        loadingImage = loadingView.findViewById(R.id.image_loading)
        retryTips =loadingView.findViewById(R.id.retryTips)
       if(retryTips!=null) {
           retryTips.setOnClickListener {
               showStateView(TYPE_LOADING, false)
               refresh()
           }
       }
        two_content.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        twoLineAdapter = CategoryAdapter(R.layout.ebook_category_item)
        two_content.adapter = twoLineAdapter

        one_content.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        oneLineAdapter = CategoryAdapter(R.layout.ebook_category_item)
        one_content.adapter = oneLineAdapter
        
        three_content.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
        threeLineAdapter = CategoryAdapter(R.layout.ebook_category_item)
        three_content.adapter = threeLineAdapter

        getTypeData()
    }

    private fun getTypeData() {
        val map = mutableMapOf<String, String>()
        map["pageNumber"] = "1"
        map["pageSize"] = "1"
        DataInvokeUtil.getZiMeiTiApi()
            .getContentList(catalogID,map)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object :Observer<Response<JSONObject>>{
                override fun onSubscribe(d: Disposable) {

                }

                override fun onNext(t: Response<JSONObject>) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    if (t.isSuccessful){
                        val body = t.body()
                        val state = body?.optBoolean("state")
                        if (state==true){
                            val data = body.optJSONObject("data")
                            data?.let{
                                val meta = data.optJSONArray("meta")
                                val nav = data.optJSONObject("navigate")
                                catId = nav.optString("catid")
                                val selectType = data.optJSONArray("content_type_selected")
                                var oneList = mutableListOf<TypeData>()
                                var twoList = mutableListOf<TypeData>()
                                var threeList = mutableListOf<TypeData>()
                                meta?.let{
                                    for(i in 0 until it.length()){
                                        val item = it.optJSONObject(i)
                                        val childAlbumTypes = item.optJSONArray("childAlbumTypes")
                                        val typeData0 = TypeData(
                                            item.optString("id"),
                                            "${item.optString("name")}")
                                        when (i) {
                                            0 -> oneList.add(typeData0)
                                            1 -> twoList.add(typeData0)
                                            else -> threeList.add(typeData0)
                                        }
                                        childAlbumTypes?.let{ child->
                                            for (j in 0 until child.length()){
                                                val childItem = child.optJSONObject(j)
                                                val typeData = TypeData(
                                                    childItem.optString("id"),
                                                    childItem.optString("name"))
                                                when (i) {
                                                    0 -> oneList.add(typeData)
                                                    1 -> twoList.add(typeData)
                                                    else -> threeList.add(typeData)
                                                }
                                            }
                                        }

                                    }
                                    oneLineAdapter.data.addAll(oneList)
                                    twoLineAdapter.data.addAll(twoList)
                                    threeLineAdapter.data.addAll(threeList)
                                    selectType?.let{
                                        for(i in 0 until it.length()){
                                            val item = it.optJSONObject(i)
                                            when (i) {
                                                0 -> oneList.forEachIndexed { index, data ->
                                                        if (item.optString("id") == data.id)
                                                            oneLineAdapter.choosePosition = index
                                                    }

                                                1 -> twoList.forEachIndexed { index, data ->
                                                    if (item.optString("id") == data.id)
                                                        twoLineAdapter.choosePosition = index
                                                }
                                                else -> threeList.forEachIndexed { index, data ->
                                                    if (item.optString("id") == data.id)
                                                        threeLineAdapter.choosePosition = index
                                                }
                                            }
                                        }
                                    }
                                    oneLineAdapter.notifyItemRangeChanged(0, oneList.size)
                                    twoLineAdapter.notifyItemRangeChanged(0, twoList.size)
                                    threeLineAdapter.notifyItemRangeChanged(0, threeList.size)
                                    if(oneList.size == 0 && twoList.size == 0 && threeList.size == 0){
                                        viewLine.visibility = View.GONE
                                        one_content.visibility = View.GONE
                                        two_content.visibility = View.GONE
                                        three_content.visibility = View.GONE
                                    }else  {
                                        viewLine.visibility = View.VISIBLE
                                        one_content.visibility = View.VISIBLE
                                        two_content.visibility = View.VISIBLE
                                        three_content.visibility = View.VISIBLE
                                    }
                                }
                                getEbookData()
                            }


                        }
                    }

                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {

                }

            })
    }

    override fun initArgs() {
        super.initArgs()
        if (fragmentArguments != null) {
            saveInstanceArguments = fragmentArguments
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        } else if (saveInstanceArguments != null) {
            catalogID = saveInstanceArguments?.getString("id")
            catalogItem = saveInstanceArguments?.getParcelable("catalog")
        }
        val navigateArgs = if (catalogItem != null && catalogItem?.navigate != null) {
            catalogItem?.navigate
        } else {
            super.navigate
        }
        navigate = navigateArgs

    }

    private fun getEbookData() {
        showStateView(TYPE_LOADING, false)
        val map = mutableMapOf<String, Any>()
        var bookTypeIds = StringBuilder()
        if (oneLineAdapter.choosePosition != 0){
            bookTypeIds.append(oneLineAdapter.data[oneLineAdapter.choosePosition].id).append(",")
        }
        if (twoLineAdapter.choosePosition != 0){
            bookTypeIds.append(twoLineAdapter.data[twoLineAdapter.choosePosition].id).append(",")
        }
        if (threeLineAdapter.choosePosition != 0){
            bookTypeIds.append(threeLineAdapter.data[threeLineAdapter.choosePosition].id)
        }
        map["bookTypeIds"] = bookTypeIds.toString()
        map["catalogIds"] = catId
        map["pageNumber"] = pageIndex
        map["pageSize"] = perPageSize
        val body =
            RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map))
        SpiderCmsApi.getSpiderCmsApi(requireContext())
            .getEbookList(body)
            .enqueue(object : Callback<BaseDataListBean<EbookData>> {
                override fun onResponse(
                    call: Call<BaseDataListBean<EbookData>>,
                    response: Response<BaseDataListBean<EbookData>>
                ) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    closeStateView()
                    if (response.body()?.isSuccess==true) {
                        val data = response.body()?.data
                        if (data!= null){
                            if(!data.isHasNextPage)  refreshLayout.setNoMoreData(true)
                            if (pageIndex == 1) {
                                ebookAdapter.data.clear()
                            }
                            val pageRecords = data.pageRecords
                            if (pageRecords!=null && pageRecords.size > 0){
                                ebookAdapter.data.addAll(pageRecords)
                            }else{
                                if (pageIndex == 1){
                                    showStateView(TYPE_NO_CONTENT,false)
                                }else
                                    ebookAdapter.data.addAll(emptyList())
                            }
                        }
                    } else {
                        showStateView(TYPE_NO_CONTENT,false)
                    }
                    ebookAdapter.notifyDataSetChanged()

                }

                override fun onFailure(call: Call<BaseDataListBean<EbookData>>, t: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    showStateView(TYPE_NET_NOT_GIVE_FORCE,false)
                }

            })
    }

    private fun refresh() {
        pageIndex = 1
        getEbookData()
//        if (chooseType) {
//            getEbookData()
//        } else {
//            load()
//        }
    }

    private fun loadMore() {
        pageIndex++
        getEbookData()
//        if (chooseType) {
//            getEbookData()
//        } else {
//            load()
//        }
    }

    private fun load() {
        Mode = REFRESH
        getTypeData()
    }

    override fun onItemClick(index: Int, isFromAdaptor: Boolean, adapter: BaseRecyclerAdapter<*>?) {
        if (isFastClick()){
            val item = ebookAdapter.getItem(index)
            val intent = Intent(requireContext(), ReadBookInfoActivity::class.java)
            intent.putExtra("EBOOK_ID",item.id)
            intent.putStringArrayListExtra("EBOOK_TYPES",item.types)
            requireContext().startActivity(intent)
        }

    }

    inner class CategoryAdapter(layoutRes: Int) : BaseQuickAdapter<TypeData, BaseViewHolder>(layoutRes) {

        var choosePosition: Int = 0

        override fun convert(helper: BaseViewHolder, item: TypeData) {
            val content: TextView = helper.getView(R.id.content)
            item?.let {
                content.text = "${it.name}"

                if (helper.adapterPosition == choosePosition) {
                    content.backgroundColor = Color.parseColor("#D43D3D")
                    content.textColor = Color.WHITE
                } else {
                    content.backgroundColor = 0
                    content.textColor = Color.parseColor("#505050")
                }
            }

            helper.itemView.setOnClickListener {
                chooseType = true
                choosePosition = helper.adapterPosition
                refresh()
                notifyDataSetChanged()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        compositeDisposable.dispose()
    }

    override fun f5() {
        recyclerView.scrollToPosition(0)
        refreshLayout.autoRefresh(200)
    }

    override fun gun() {

    }
}